package com.jiacl.service.impl;

import com.jiacl.core.CommonConstants;
import com.jiacl.entity.JiaclArea;
import com.jiacl.entity.core.Result;
import com.jiacl.mapper.JiaclAreaMapper;
import com.jiacl.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by XiaoWei on 2017/9/1.
 */
@Service
public class AreaServiceImpl implements AreaService{

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private JiaclAreaMapper jiaclAreaMapper;



    @Override
    public Result getArea(Long id) {
        if(id<0){
            return new Result();
        }
        Object redisCache = redisTemplate.opsForValue().get(CommonConstants.AREA_REDIS_KEY + id);
        if (!StringUtils.isEmpty(redisCache)) {
            return new Result(redisCache);
        }
        JiaclArea jiaclArea = jiaclAreaMapper.selectByPrimaryKey(id);
        redisTemplate.opsForValue().set(CommonConstants.AREA_REDIS_KEY+id,jiaclArea,1, TimeUnit.DAYS);
        return new Result(jiaclArea);
    }

    @Override
    public Result getAreaByParent(Long parentId) {
        if(parentId<0){
            return new Result();
        }
        Object redisCache = redisTemplate.opsForValue().get(CommonConstants.AREA_BY_PARENT_ID_REDIS_KEY + parentId);
        if (!StringUtils.isEmpty(redisCache)) {
            return new Result(redisCache);
        }
        List<JiaclArea> jiaclAreas = jiaclAreaMapper.selectByParentId(parentId);
        redisTemplate.opsForValue().set(CommonConstants.AREA_BY_PARENT_ID_REDIS_KEY+parentId,jiaclAreas,1, TimeUnit.DAYS);
        return new Result(jiaclAreas);
    }
}
